﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using log4net;
using McsUtility;

namespace MinerManager.Forms
{
	public partial class MinerConfiguration : DevExpress.XtraEditors.XtraForm
	{
		ILog logger = LogManager.GetLogger(typeof(Program));
		private Common.AgentComponent Agent = null;
		private Models.MinerModel Model = null;

		public event EventHandler<ObjectEventArgs> OnSuccess;

		public MinerConfiguration(Common.AgentComponent agent, Models.MinerModel model)
		{
			InitializeComponent();
			this.Agent = agent;
			this.Model = model;
		}

		#region 窗体事件

		private void MinerConfiguration_Load(object sender, EventArgs e)
		{
			ItemMinerName.Text = this.Model.MinerName;
			ItemAutoName.Checked = this.Model.AutoName;
			ItemAutoUpdate.Checked = this.Model.AutoUpdate;
			ItemAdvParams.Text = this.Model.AdvParams;
			SecondEnable.Checked = this.Model.Second;
			ItemHighTempStrategy.EditValue = (int)this.Model.HighTempStrategy;
			ItemHighTempWarn.Checked = this.Model.HighTempWarn;
			ItemLowStrengthWarn.Checked = this.Model.LowStrengthWarn;
			ItemCoreType.EditValue = (int)this.Model.CoreType;

			ItemAutoName_CheckedChanged(this, null);

			//最高温度
			List<ComboboxListItem> itemsMaxTemp = new List<ComboboxListItem>()
			{
				new ComboboxListItem("70", "70"),
				new ComboboxListItem("75", "75"),
				new ComboboxListItem("80", "80"),
				new ComboboxListItem("85", "85"),
				new ComboboxListItem("90", "90")
			};
			Utility.Forms.SetComboBoxEdit(this, "ItemMaxTemp", itemsMaxTemp, this.Model.MaxTemp);

			//最低转速
			List<ComboboxListItem> itemsMinFan = new List<ComboboxListItem>();
			itemsMinFan.Add(new ComboboxListItem("驱动智能控制", "0"));
			for (int i = 40; i <= 100; i += 5)
			{
				itemsMinFan.Add(new ComboboxListItem(i.ToString(), i.ToString()));
			}
			Utility.Forms.SetComboBoxEdit(this, "ItemMinFan", itemsMinFan, this.Model.MinFan);

			//总算力预警值
			List<ComboboxListItem> itemsMinSpeed = new List<ComboboxListItem>();
			for (int i = 5; i <= 500; i += 5)
			{
				itemsMinSpeed.Add(new ComboboxListItem(i.ToString(), i.ToString()));
			}
			Utility.Forms.SetComboBoxEdit(this, "ItemMinSpeed", itemsMinSpeed, this.Model.MinSpeed);

			//主币币种
			List<ComboboxListItem> itemsFirstCurrency = new List<ComboboxListItem>();
			foreach (McsUtility.Models.CurrencysModel info in Common.Data.UserCurrency.Where(p => p.Type == 1))
			{
				itemsFirstCurrency.Add(new ComboboxListItem(info.Remark, info.Name));
			}
			Utility.Forms.SetComboBoxEdit(this, "FirstCurrency", itemsFirstCurrency, this.Model.FirstCoin);

			//辅币币种
			List<ComboboxListItem> itemsSecondCurrency = new List<ComboboxListItem>();
			foreach (McsUtility.Models.CurrencysModel info in Common.Data.UserCurrency.Where(p => p.Type == 2))
			{
				itemsSecondCurrency.Add(new ComboboxListItem(info.Remark, info.Name));
			}
			Utility.Forms.SetComboBoxEdit(this, "SecondCurrency", itemsSecondCurrency, this.Model.SecondCoin);

			//算力比重
			List<ComboboxListItem> itemsDcri = new List<ComboboxListItem>();
			for (int i = 0; i <= 50; i += 5)
			{
				int num = i > 0 ? i : 1;
				itemsDcri.Add(new ComboboxListItem(num.ToString(), num.ToString()));
			}
			Utility.Forms.SetComboBoxEdit(this, "SecondDcri", itemsDcri, !string.IsNullOrWhiteSpace(this.Model.Dcri) ? this.Model.Dcri : "20");
		}

		private void MinerConfiguration_FormClosing(object sender, FormClosingEventArgs e)
		{
		}

		#endregion

		#region void ItemAutoName_CheckedChanged(object sender, EventArgs e)

		private void ItemAutoName_CheckedChanged(object sender, EventArgs e)
		{
			ItemMinerName.Enabled = !ItemAutoName.Checked;
		}

		#endregion

		#region void FirstCurrency_SelectedIndexChanged(object sender, EventArgs e)

		private void FirstCurrency_SelectedIndexChanged(object sender, EventArgs e)
		{
			ComboboxListItem item = FirstCurrency.SelectedItem as ComboboxListItem;
			if (item != null)
			{
				McsUtility.Models.CurrencysModel info = Common.Data.UserCurrency.Where(p => p.Name.Equals(item.Value, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
				if (info != null)
				{
					//钱包信息
					List<ComboboxListItem> itemsWallet = new List<ComboboxListItem>();

					//矿池信息
					List<ComboboxListItem> itemsPool = new List<ComboboxListItem>();

					foreach (McsUtility.Models.WalletsModel infoWallet in info.Wallets)
					{
						itemsWallet.Add(new ComboboxListItem(infoWallet.Address, infoWallet.Address));
					}

					foreach (McsUtility.Models.WalletsModel infoPool in info.OrePools)
					{
						string poolName = (!string.IsNullOrWhiteSpace(infoPool.Remark) ? infoPool.Remark + " " : "") + infoPool.Address;
						itemsPool.Add(new ComboboxListItem(poolName, infoPool.Address));
					}

					//下拉框默认值
					string firstPool = string.Empty;

					if (itemsPool.FindIndex(p => p.Value.Equals(this.Model.FirstPool)) >= 0)
						firstPool = this.Model.FirstPool;

					string firstBackupPool = string.Empty;
					if (itemsPool.FindIndex(p => p.Value.Equals(this.Model.BackupPool)) >= 0)
						firstBackupPool = this.Model.BackupPool;

					string firstWallet = string.Empty;
					if (itemsWallet.FindIndex(p => p.Value.Equals(this.Model.FirstWallet)) >= 0)
						firstWallet = this.Model.FirstWallet;

					//赋值显示
					Utility.Forms.SetComboBoxEdit(this, "FirstPool", itemsPool, firstPool);
					Utility.Forms.SetComboBoxEdit(this, "FirstBackupPool", Utility.Clone(itemsPool), firstBackupPool);
					Utility.Forms.SetComboBoxEdit(this, "FirstWallet", itemsWallet, firstWallet);
				}
			}
		}

		#endregion

		#region void SecondCurrency_SelectedIndexChanged(object sender, EventArgs e)

		private void SecondCurrency_SelectedIndexChanged(object sender, EventArgs e)
		{
			ComboboxListItem item = SecondCurrency.SelectedItem as ComboboxListItem;
			if (item != null)
			{
				McsUtility.Models.CurrencysModel info = Common.Data.UserCurrency.Where(p => p.Name.Equals(item.Value, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
				if (info != null)
				{
					//钱包信息
					List<ComboboxListItem> itemsWallet = new List<ComboboxListItem>();

					//矿池信息
					List<ComboboxListItem> itemsPool = new List<ComboboxListItem>();

					foreach (McsUtility.Models.WalletsModel infoWallet in info.Wallets)
					{
						itemsWallet.Add(new ComboboxListItem(infoWallet.Address, infoWallet.Address));
					}

					foreach (McsUtility.Models.WalletsModel infoPool in info.OrePools)
					{
						string poolName = (!string.IsNullOrWhiteSpace(infoPool.Remark) ? infoPool.Remark + " " : "") + infoPool.Address;
						itemsPool.Add(new ComboboxListItem(poolName, infoPool.Address));
					}

					//下拉框默认值
					string secondPool = string.Empty;
					if (itemsPool.FindIndex(p => p.Value.Equals(this.Model.SecondPool)) >= 0)
						secondPool = this.Model.SecondPool;

					string secondWallet = string.Empty;
					if (itemsWallet.FindIndex(p => p.Value.Equals(this.Model.SecondWallet)) >= 0)
						secondWallet = this.Model.SecondWallet;

					//赋值显示
					Utility.Forms.SetComboBoxEdit(this, "SecondPool", Utility.Clone(itemsPool), secondPool);
					Utility.Forms.SetComboBoxEdit(this, "SecondWallet", Utility.Clone(itemsWallet), secondWallet);
				}
			}
		}

		#endregion

		#region void BtnSave_Click(object sender, EventArgs e)

		private void BtnSave_Click(object sender, EventArgs e)
		{
			decimal minSpeed = 0;
			decimal.TryParse(ItemMinSpeed.Text, out minSpeed);

			#region 非法信息检测

			if (!ItemAutoName.Checked && string.IsNullOrWhiteSpace(ItemMinerName.Text))
			{
				if (MessageBox.Show("请填写矿机名。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error) == DialogResult.OK)
				{
					ItemMinerName.Focus();
					ItemMinerName.SelectAll();
				}
				return;
			}

			if (ItemLowStrengthWarn.Checked && minSpeed < 0)
			{
				if (MessageBox.Show("请填写正确的算力预警值。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error) == DialogResult.OK)
				{
					ItemMinSpeed.Focus();
					ItemMinSpeed.SelectAll();
				}
				return;
			}
			
			if (FirstCurrency.SelectedItem == null || string.IsNullOrWhiteSpace(((ComboboxListItem)FirstCurrency.SelectedItem).Value))
			{
				if (MessageBox.Show("请选择主币币种。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error) == DialogResult.OK)
				{
					FirstCurrency.Focus();
					FirstCurrency.SelectAll();
				}
				return;
			}

			if (FirstPool.SelectedItem == null || string.IsNullOrWhiteSpace(((ComboboxListItem)FirstPool.SelectedItem).Value))
			{
				if (MessageBox.Show("请选择主币矿池。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error) == DialogResult.OK)
				{
					FirstPool.Focus();
					FirstPool.SelectAll();
				}
				return;
			}

			if (FirstWallet.SelectedItem == null || string.IsNullOrWhiteSpace(((ComboboxListItem)FirstWallet.SelectedItem).Value))
			{
				if (MessageBox.Show("请选择主币钱包。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error) == DialogResult.OK)
				{
					FirstWallet.Focus();
					FirstWallet.SelectAll();
				}
				return;
			}

			if (SecondEnable.Checked)
			{
				if (SecondCurrency.SelectedItem == null || string.IsNullOrWhiteSpace(((ComboboxListItem)SecondCurrency.SelectedItem).Value))
				{
					if (MessageBox.Show("请选择辅币币种。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error) == DialogResult.OK)
					{
						SecondCurrency.Focus();
						SecondCurrency.SelectAll();
					}
					return;
				}

				if (SecondPool.SelectedItem == null || string.IsNullOrWhiteSpace(((ComboboxListItem)SecondPool.SelectedItem).Value))
				{
					if (MessageBox.Show("请选择辅币矿池。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error) == DialogResult.OK)
					{
						SecondPool.Focus();
						SecondPool.SelectAll();
					}
					return;
				}

				if (SecondWallet.SelectedItem == null || string.IsNullOrWhiteSpace(((ComboboxListItem)SecondWallet.SelectedItem).Value))
				{
					if (MessageBox.Show("请选择辅币钱包。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error) == DialogResult.OK)
					{
						SecondWallet.Focus();
						SecondWallet.SelectAll();
					}
					return;
				}
			}

			#endregion

			//内核
			McsUtility.Models.CoreType coreType = (McsUtility.Models.CoreType)Enum.Parse(typeof(McsUtility.Models.CoreType), ItemCoreType.EditValue.ToString());

			//发送数据
			if (this.Agent.IsStarted)
			{
				this.Model.AutoUpdate = ItemAutoUpdate.Checked;
				this.Model.AutoName = ItemAutoName.Checked;
				this.Model.MinerName = ItemMinerName.Text;
				this.Model.MinFan = ((ComboboxListItem)ItemMinFan.SelectedItem).Value;
				this.Model.MaxFan = "100";
				this.Model.MinTemp = "";
				this.Model.MaxTemp = ((ComboboxListItem)ItemMaxTemp.SelectedItem).Value;
				this.Model.HighTempStrategy = (McsUtility.Models.HighTempStrategy)Enum.Parse(typeof(McsUtility.Models.HighTempStrategy), ItemHighTempStrategy.EditValue.ToString());
				this.Model.HighTempWarn = ItemHighTempWarn.Checked;
				this.Model.LowStrengthWarn = ItemLowStrengthWarn.Checked;
				this.Model.MinSpeed = minSpeed.ToString();
				this.Model.CoreType = coreType;
				this.Model.FirstCoin = ((ComboboxListItem)FirstCurrency.SelectedItem).Value;
				this.Model.FirstPool =((ComboboxListItem)FirstPool.SelectedItem).Value;
				this.Model.BackupPool = ((ComboboxListItem)FirstBackupPool.SelectedItem).Value;
				this.Model.FirstWallet = ((ComboboxListItem)FirstWallet.SelectedItem).Value;
				this.Model.Second = SecondEnable.Checked;
				this.Model.Dcri = ((ComboboxListItem)SecondDcri.SelectedItem).Value;
				this.Model.SecondCoin = SecondCurrency.SelectedItem != null ? ((ComboboxListItem)SecondCurrency.SelectedItem).Value : "";
				this.Model.SecondPool = SecondEnable.Checked ? ((ComboboxListItem)SecondPool.SelectedItem).Value : "";
				this.Model.SecondWallet = SecondEnable.Checked ? ((ComboboxListItem)SecondWallet.SelectedItem).Value : "";
				this.Model.AdvParams = ItemAdvParams.Text;
				this.Model.Eres = "";

				McsUtility.Models.MinersMiningRequestModel info = new McsUtility.Models.MinersMiningRequestModel
				{
					MinersIDs = new List<int> { this.Model.ID },
					AutoRun = false,
					AutoName = this.Model.AutoName,
					AutoUpdate = this.Model.AutoUpdate,
					MinerName = this.Model.MinerName,
					MinFan = this.Model.MinFan,
					MaxFan = this.Model.MaxFan,
					MinTemp = this.Model.MinTemp,
					MaxTemp = this.Model.MaxTemp,
					HighTempStrategy = this.Model.HighTempStrategy,
					HighTempWarn = this.Model.HighTempWarn,
					LowStrengthWarn = this.Model.LowStrengthWarn,
					MinSpeed = this.Model.MinSpeed,
					CoreType = this.Model.CoreType,
					FirstCoin = this.Model.FirstCoin,
					FirstPool = this.Model.FirstPool,
					BackupPool = this.Model.BackupPool,
					FirstWallet = this.Model.FirstWallet,
					Second = this.Model.Second,
					Dcri = this.Model.Dcri,
					SecondCoin = this.Model.SecondCoin,
					SecondPool = this.Model.SecondPool,
					SecondWallet = this.Model.SecondWallet,
					AdvParams = this.Model.AdvParams,
					Eres = this.Model.Eres
				};

				byte[] bytes = ProtocolHelper.WritePackage<McsUtility.Models.MinersMiningRequestModel>(ProtoType.MinerManagerModifyOrePoolUrl, info);
				this.Agent.AgentSend(bytes);
				OnSuccess?.Invoke(this, new ObjectEventArgs(this.Model));
			}
			else
			{
				MessageBox.Show("与服务器的链接断开，请重新登录系统。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
			}
		}

		#endregion

		#region void BtnClose_Click(object sender, EventArgs e)

		private void BtnClose_Click(object sender, EventArgs e)
		{
			this.Close();
		}

		#endregion
	}
}